package org.rockwalrus.ruly;

import static org.rockwalrus.ruly.Time.TIME_ZONE;

import java.text.SimpleDateFormat;
import java.util.logging.Logger;

import com.google.wave.api.AbstractRobot;
import com.google.wave.api.Blip;
import com.google.wave.api.Context;
import com.google.wave.api.event.DocumentChangedEvent;
import com.google.wave.api.event.WaveletSelfAddedEvent;

@SuppressWarnings("serial")
public class RulyServlet extends AbstractRobot {
    private static final Logger log = Logger.getLogger(RulyServlet.class.getName());

    
    static final int VOTING_PERIOD = 48;
    private static final Handler[] handlers = new Handler[] {
	new VotingHandler("proposal:", "PROPOSAL:", "proposal"),
	new VotingHandler("judgement:", "JUDGEMENT REQUEST:", "judgement request"),
	new ParentBasedVotingHandler("patch:", "PATCH PROPOSAL:", "patch proposal"),
	new ElectionHandler("election:", "ELECTION:", "election")
    };
    
    @Override
    public void onWaveletSelfAdded(WaveletSelfAddedEvent event) {
        StringBuilder helpText = new StringBuilder();
        
        for (Handler handler : handlers) {
            helpText.append('\n');
            helpText.append(handler.getHelpText());
        }
        
        event.getWavelet().reply(helpText.toString());
    }
    
    @Override
    @Capability(contexts=Context.ALL)
    public void onDocumentChanged(DocumentChangedEvent event) {
        SimpleDateFormat f = new SimpleDateFormat("'on' EEEE, MMMM d, yyyy 'at' h:mm a zzzz.");
        f.setTimeZone(TIME_ZONE);        
        Blip document = event.getBlip();
        String text = document.getContent();

        for (Handler handler : handlers) {
            if (handler.isTriggered(text)) {
                handler.handleBlip(f, event, document);
                break;
            }
        }
    }

    @Override
    protected String getRobotName() {
        return "Ruly";
    }
}